import base from "./base";
import {toJS} from "mobx";
import React from 'react';
import {ActionSheet, Bubble, Toast} from 'weaver-mobile';
import * as EmSDK from "./emSDK";
import * as VariableKeys from "../constants/variableKey";
import * as SignUtil from "./SignUtil";
import * as rightBtn from './rightBtn';
import {getLabel} from './common';
import * as API_SUPERVISE from '../apis/supervise';
import {GlobalUtil} from './pcPublic';
import {filterRequest4Forward} from "../util/secondAuthUtil";
import isEmpty from 'lodash/isEmpty';
//客户端调用
window.rightBtn = rightBtn;

/**
 * 获取底部按钮
 */
export const getEmBottomBtns = () => {
    const wfOperateStore = base.wfOperateStore;
    const {wfSignInputStore} = base.allStores;
    const { requestType, intervenorright,isHideInput = '0'} = base.wfGlobalStore.commonParam;
    const { ismonitor = 0 } = base.wfGlobalStore.urlParams;
    const { rightMenu, markInfo = {}, btnDisabled } = wfOperateStore;
    const {isurger = false} = wfSignInputStore;
    const rightMenus = toJS(rightMenu.rightMenus || []);
    let isIntervenor = false;
    rightMenus.map(item => {
        if (item.menuFun && item.menuFun.includes("doIntervenor")) {
            isIntervenor = true;
        }
    })
    const isshowsigninput = (requestType > 0 || isurger || isIntervenor) && isHideInput != '1';
    const showSignBtn = isshowsigninput ? SignUtil.getVariableMapVal(VariableKeys.SHOW_SIGN_BTN, true) : false;
    const { fowardSubmitParams = {}, isForwad, showSignInput, setShowIconBtnList} = wfSignInputStore;
    let showMoreBtn = true;
    const showSignArea = SignUtil.getVariableMapVal(VariableKeys.SHOW_SIGN_AREA, false);
    // const currOperateType = SignUtil.getVariableMapVal(VariableKeys.CURR_OPERATE_TYPE,{});
    /**
     * 这里的CURR_OPERATE_TYPE，原本只是保存的按钮的type，但是当有多个自定义按钮时，type不唯一，
     * 签字意见框弹出时，就会展示多个按钮，因此这里改为保存按钮的所有相关信息，item，
     * 下方需要显示时，就直接可以从item里获取信息，不需要再遍历rightMenus，用type去匹配获取item信息
     * add by fmj
     */
    const currOperateItem = SignUtil.getVariableMapVal(VariableKeys.CURR_OPERATE_TYPE,{});
    const bottomBtns = [];
    let urger = isurger && showSignArea;
    //base.wfGlobalStore.commonParam.isurger = urger;已沟通这个操作应该没用了
    //转发
    if (isForwad || urger) {
        let forwardBtnName = '';
        if(isForwad){
            const {forwardflag = '1'} = fowardSubmitParams;
            //自定义按钮信息
            const {customBtnInfo = {}} = markInfo;
            const {btnNameInfo = {}} = customBtnInfo;
            let actionName = btnNameInfo[forwardflag] || '';

            if (forwardflag == '1') forwardBtnName = getLabel(500322,'转发提交');
            if (forwardflag == '2') forwardBtnName = getLabel(500323,'意见征询提交');
            if (forwardflag == '3') forwardBtnName = getLabel(500324,'转办提交');
            if (forwardflag == '4') forwardBtnName = getLabel(503516,'传阅提交');
            if (forwardflag == '5') forwardBtnName = getLabel(507272,'征询转办') + getLabel(615,'提交');
            
            if(actionName.length > 0){
                forwardBtnName = `${actionName}${getLabel(615,'提交')}`;
            }
            bottomBtns.push({
                'key': 'forward', 'image': '', 'name': forwardBtnName, 'action': () => {
                    if(btnDisabled)return;
                    dofowardSubmit()
                }
            })
        }
        if(urger){
            forwardBtnName = getLabel(21223,'督办')
            bottomBtns.push({
                'key': 'supervise', 'image': '', 'name': forwardBtnName, 'action': () => {
                    if(btnDisabled)return;
                    doSupervise()
                }
            })
        }
    } else {
        //意见
        if (showSignBtn) {
            bottomBtns.push({
                'key': 'remark', 'image': '/images/ecology9/workflow/em-input-remark.png', 'name': '', 'action': () => {
                  showSignInput({}, 'yijian')
                }, 'flex': 4
            });
        }

        if(!isEmpty(currOperateItem) /*currOperateType != ''*/ && showSignArea) {
            showMoreBtn = false;
            /*rightMenus.map((v = {}, i) => {//取右键前2个操作做为底部按钮
                const { type, menuName, isTop = '0' } = v;
                if(type == currOperateType) {
                    bottomBtns.push({
                        'key': v.type, 'image': '', 'name': v.menuName, 'action': () => {
                            triggerBlur();
                            doRightMenuClick(v)
                        }, 'flex': 6
                    })
                }
            });*/

            bottomBtns.push({
                'key': currOperateItem.type, 'image': '', 'name': currOperateItem.menuName, 'action': () => {
                    if(btnDisabled)return;
                    triggerBlur();
                    doRightMenuClick(currOperateItem)
                }, 'flex': 6
            })
        } else {
            let count = showSignBtn ? 3 : 2;
            rightMenus.map((v = {}, i) => {//取右键前2个操作做为底部按钮
                const { type, menuName, isTop = '0' } = v;
                if ((isTop == '1' || ismonitor == 1) && bottomBtns.length < count) {
                    bottomBtns.push({
                        'key': v.type, 'image': '', 'name': v.menuName, 'action': () => {
                            if(btnDisabled)return;
                            triggerBlur();
                            doRightMenuClick(v)
                        }, 'flex': 6
                    })
                }
            });
        }
        // if (rightMenus.length < 3) showMoreBtn = false;

        //更多
        if (showMoreBtn && rightMenus.length > 2) {
            const moreBtn = {'key': 'more', 'image': '', 'name': getLabel(17499,'更多')};
            if (EmSDK.judgeApiSupport('showBottomToolBar')) {
                let moreRightMenus = rightMenus.splice(2);
                const btnItems = [];
                moreRightMenus.map((v) => {
                    let btn = {
                        'name': v.menuName, 'image': '', 'action': () => {
                            if(btnDisabled)return;
                            triggerBlur();
                            doRightMenuClick(v)
                        }
                    };
                    if(v.systemMenuType == "REJECT"){
                        btnItems.unshift(btn);
                    } else {
                        btnItems.push(btn)
                    }
                })
                moreBtn.subItems = btnItems;
                moreBtn.showType = 1;
            } else {
                moreBtn.action = () => {
                    if(btnDisabled)return;
                    showActionSheet()
                }
                moreBtn.flex = 4;
            }
            if (isurger) {
                showSignBtn && bottomBtns.push(moreBtn);
            } else {
                bottomBtns.push(moreBtn);
            }
        }
    }
    
    return bottomBtns;
}

//触发失去焦点事件
export const triggerBlur = () => {
    try{
        const activeElm = window.document.activeElement;
        if(activeElm.tagName === "INPUT" || activeElm.tagName === "TEXTAREA")
            activeElm.blur();
    }catch(e){}
}

export const doSupervise = () =>{
    const {  wfSignInputStore ,wfOperateStore} = base.allStores;
	const { batchControlVariableMap, showSignInput,hiddenSignInput,forwardClear,ckStore} = wfSignInputStore;
    const { wfGlobalStore } = base;
    const { requestid,f_weaver_belongto_userid } = wfGlobalStore.commonParam;
    const {markInfo = {},isRichText} = wfOperateStore;
    const {isSignMustInput = ''} = markInfo;
    let remark = SignUtil.getVariableMapVal(VariableKeys.SIGN_CONTENT);
    if(isRichText && ckStore.isInited) {
        remark = ckStore.getData();
    }
    let _remark = SignUtil.remarkFilter(remark);
    let flag  = true;
    if(isSignMustInput == '1' || (isSignMustInput == '2' && SignUtil.verifyRemarkMustInput('supervise'))) {
        flag = SignUtil.checkRemark(remark) || SignUtil.remarkCanBeEmpty(false);
    }
    if(flag) {
        //处理引用
        const remarkQuote = SignUtil.getRemarkQuoteData(_remark);
        let tempRequestid = requestid.toString() + '_' + f_weaver_belongto_userid.toString();
        const params = {requestids: tempRequestid, ...remarkQuote, ...SignUtil.getSignInfoDatas()};
        wfGlobalStore.setLoading(true);
        API_SUPERVISE.doSupervise(params).then(data => {
            wfGlobalStore.setLoading(false);
            if (data.result) {
                Bubble.success(getLabel(387108, '督办成功'));

                //清空签字意见
                let updateParams = {};
                updateParams[VariableKeys.SIGN_CONTENT] = '';
                hiddenSignInput(updateParams);

                setTimeout(() => {
                    //刷新签字意见区域
                    const reloadLogListParams = {pgnumber: 1, atmet: '', maxrequestlogid: 0};
                    const {updateLogParams, activeKey, setState} = base.allStores.wfSignListStore;
                    if (activeKey != '1') setState({activeKey: '1'});
                    updateLogParams(reloadLogListParams, true);
                }, 200);
            } else {
                Bubble.error(getLabel(387109, '督办失败'));
            }
        });
    } else {
        Toast.info(getLabel(500238,'请输入签字意见！'), 1);
    }
}

//转发提交
export const dofowardSubmit = () => {
    const {wfOperateStore,allStores} = base;
    const {secondAuthStore,wfSignInputStore} = allStores;
    const {markInfo = {},isRichText} = wfOperateStore;
    const signParams = toJS(markInfo);
    const {remarkInfo = {}, isSignMustInput, IsSubmitedOpinion, IsBeForwardTodo} = signParams;
    //验证签字意见必填
    const {forwardOperatorDatas, fowardSubmitParams = {},ckStore} = wfSignInputStore;
    const {forwardflag = '1'} = fowardSubmitParams;
    //自定义按钮信息
    const {customBtnInfo = {}} = markInfo;
    const {btnNameInfo = {}, overTimeTakInfo = {}} = customBtnInfo;
    let _actionName = btnNameInfo[forwardflag] || '';

    let actionName = getLabel(6011,'转发');
    if (forwardflag == '2') actionName = getLabel(82578,'意见征询');
    if (forwardflag == '3') actionName = getLabel(23745,'转办');
    if (forwardflag == '4') actionName = getLabel(23028,'传阅');
    if (forwardflag == '5') actionName = getLabel(507272,'征询转办');

    
    if(_actionName.length > 0){
        actionName = _actionName;
    }


    if (forwardOperatorDatas.length == 0) {
        Toast.info(`${getLabel(18214,'请选择')}${actionName}${getLabel(15525,'接收人')}！`, 2);
        return;
    }
    if (verifyRemarkMustInput(signParams,forwardflag)) {
        let forwardremark = SignUtil.getVariableMapVal(VariableKeys.FORWARD_SIGN_CONTENT, '');
        if(isRichText && ckStore.isInited) {
            forwardremark = ckStore.getData();
        }

        if (!SignUtil.checkRemark(forwardremark) && !SignUtil.remarkCanBeEmpty(true)) {
            Toast.info(`${getLabel(23073,'请填写')}${actionName}${getLabel(504,'意见')}！`, 2);
            return;
        }
    }

    if(fowardSubmitParams.isOpenTakOvertime == 1 && !fowardSubmitParams.takOverHours && !fowardSubmitParams.takOverMins) {
        Toast.info(overTimeTakInfo && overTimeTakInfo[3], 2);
        return;
    }

    const {requestid, nodeid, currentnodetype, requestType} = base.wfGlobalStore.commonParam;
    const forwardParams = {requestid, nodeid, operate: 'save'};
    if (currentnodetype == "3") { //办结
        forwardParams.IsBeForwardSubmitNotaries = IsSubmitedOpinion;
        forwardParams.IsBeForward = IsBeForwardTodo;
    } else {
        if (requestType == "1") { //待办
            forwardParams.IsSubmitedOpinion = IsSubmitedOpinion;
            forwardParams.IsBeForwardTodo = IsBeForwardTodo;
        } else { //已办
            forwardParams.IsBeForwardSubmitAlready = IsSubmitedOpinion;
            forwardParams.IsBeForwardAlready = IsBeForwardTodo;
        }
    }

    const {submitParam} = wfOperateStore;
    const {workflowid, f_weaver_belongto_userid, f_weaver_belongto_usertype} = submitParam;
    const secondAuthParam = {
        workflowid,
        nodeid,
        requestid,
        f_weaver_belongto_userid,
        f_weaver_belongto_usertype
    };
    wfSignInputStore.setSecondAuthParams(secondAuthParam, secondAuthStore, filterRequest4Forward);
    wfSignInputStore.forwardSubmit(forwardParams);
}

const verifyRemarkMustInput = (signinput = {},forwardflag = '1') => {
    const {signMustInputTypes = [],isSignMustInput = ''} = signinput;
    if(isSignMustInput == '1') {
        return true;
    } else if(isSignMustInput == '2') {
        return signMustInputTypes.indexOf(`forwardflag${forwardflag}`) > -1;
    } else {
        return false;
    }
}

//按钮点击
export const doRightMenuClick = (item) => {
    const {controlVariableMap} = base.allStores.wfSignInputStore;
    const {type = ''} = item;
    const excludeType = ['BTN_MONITOR','BTN_SHARE','BTN_ATTENTION','BTN_SUPERVISE_SMS','BTN_SUPERVISE_EMAIL','BTN_DING'];
    if(excludeType.indexOf(type) == -1) {
        controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,item);
    }
    GlobalUtil.executeRightBtnClick(item,rightBtn);
}

export const showActionSheet = () => {
    const wfOperateStore = base.wfOperateStore;
    const {rightMenu, btnDisabled} = wfOperateStore;

    let rightMenus = toJS(rightMenu.rightMenus || []);
    rightMenus = rightMenus.splice(2);
    const btns = [];
    rightMenus.map(v => {
        let btn = {
            content: btnDisabled ? React.createElement('div', {className: "wf-rightbtn-disabled"}, v.menuName) : v.menuName
        };
        if(v.systemMenuType == "REJECT"){
            btns.unshift(btn);
        } else {
            btns.push(btn);
        }
    });
    btns.push({content: getLabel(31129,'取消')});
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let wrapProps;
    if (isIPhone) {
        wrapProps = {
            onTouchStart: e => e.preventDefault(),
        };
    }
    ActionSheet.showActionSheetWithOptions({
            options: btns,
            cancelButtonIndex: btns.length - 1,
            destructiveButtonIndex: btns.length - 1,
            // destructiveButtonIndex: [1,2],
            // title: 'title',
            // message: 'I am description, description, description',
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        },
        (buttonIndex) => {
            if (buttonIndex != rightMenus.length && buttonIndex != -1) {
                let menuInfo = rightMenus[buttonIndex];
                doRightMenuClick(menuInfo, buttonIndex);
            }
        }
    );
}